import os
import re
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.db import djangoforms
from google.appengine.api import mail
from xml.sax import saxutils
from datetime import datetime


import django
from django import http
from django import shortcuts
from django.template import loader
from blog.models import *
from blog.sessions import *
from blog.relativedelta import *
from conf.settings import *
from util import I18NRequestHandler

def respond(request, user, template, params=None):
   
    session = Session()
    user = users.GetCurrentUser()
    
    if user:
        params['user'] = user
        params['sign_out'] = users.CreateLogoutURL('/')
        params['is_admin'] = users.IsCurrentUserAdmin()
        member = Permission(1)
        if member is None:
            member = CreateMember(None)
            if member is None:
                return http.HttpResponseRedirect('/user/vmember/add')
            else:
                return http.HttpResponseRedirect('/')
        params['member'] = member  
    else:
        params['sign_in'] = users.CreateLoginURL(request.path)
    
    if not template.endswith('.html'):
        template += '.html'
    #List Cate
    optionCate = ListOptionCate(0,'==',None,True)
    params['listCate'] = optionCate
    
    return shortcuts.render_to_response(template, params)

def respondMember(request, user, template, params=None):
   
    session = Session()
    user = users.GetCurrentUser()
    
    if user:
        params['user'] = user
        params['sign_out'] = users.CreateLogoutURL('/')
        params['is_admin'] = users.IsCurrentUserAdmin()
        member = Permission(1)
        if member is None:
            member = CreateMember(None)
        params['member'] = member
    else:
        params['sign_in'] = users.CreateLoginURL(request.path)
    
    if not template.endswith('.html'):
        template += '.html'
    #List Cate
    optionCate = ListOptionCate(0,'==',None,True)
    params['listCate'] = optionCate
    
    return shortcuts.render_to_response(template, params)

def count_page(total, n):
    if (total % n == 0): 
        return (int)(total / n)
    return (int)(total / n) + 1
  
def paging(total, link, nitem, itemcurrent, step=10, script=''):
    
    ret = ''
    param = ''

    pages = count_page(total, nitem)
    
    if (itemcurrent > 1): 
        ret += '<a title="First" href="%s0%s" class="lslink">[&lt;&lt;]</a> ' % (link, script)
    if (itemcurrent > 2): 
        ret += '<a title="Previous" href="%s%d%s" class="lslink">[&lt;]</a> ' % (link, itemcurrent - 1, script)
    
    if (itemcurrent - step) > 0 :
        fr = itemcurrent - step
    else:
        fr = 0
    
    if (itemcurrent + step) < pages :
        to = itemcurrent + step
    else:
        to = pages
    
    for i in range (fr, to):
        if (i != itemcurrent - 1):
            ret += '<a href="%s%d%s" >%d</a> ' % (link, i, script, i + 1)
        else: 
             ret += '<b>%d</b>' % (i + 1)
    
    if ((itemcurrent < pages - 2) & (pages > 1)):
        ret += '<a title="Next" href="%s%d%s" >[&gt;]</a> ' % (link, itemcurrent + 1, script)
    if (itemcurrent < pages - 1):
        ret += '<a title="Last" href="%s%d%s" >[&gt;&gt;]</a> ' % (link, pages - 1, script)
     
    
    return ret




def ListArray(name, items, key, value, all=None, checked=None):
    string = '<select size="1" id="' + name + '" name="' + name + '">';
    if all is not None:
        string += '<option value="" >' + all + '</option>';
    
    if checked is None:
        checked = 0
    
    for item in items:

        # set value 
        if key == 'id':
            v = str(item.key().id())
        else:
            v = getattr(item, key)
        #set name
        n = getattr(item, value)
        
        if int(item.key().id()) == int(checked) :
                string += '<option value="' + v + '" selected="true">' + n + '</option>';
        else:
            string += '<option value="' + v + '" >' + n + '</option>';
    string += '</select>'
    return string

def tagify(tag, val):
    return "<%s>%s</%s>" % (tag, val, tag)
    
def render_val(rec, field):
    return saxutils.escape(unicode(getattr(rec, field)))

   

def get_safe(request, name, default=None, type='POST'):
    value = default
    if type == 'POST':
        if request.POST.get(name):
            value = request.POST.get(name)
    else:
        if request.GET.get(name):
            value = request.POST.get(name)
    return value
    
def getConfig(name):
    value = None
    config = Config.gql('WHERE name=:1', name).get()
    if config:
        return config.value
    return value

def ValidateEmail(email):
    if len(email) > 7:
        if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email) != None:
            return True
    return False
def SafeGet(name, default, request):
    if request.GET.get(name):
        return request.GET.get(name)
    else:
        return default
def SafePost(name, default, request):
    if request.POST.get(name):
        return request.POST.get(name)
    else:
        return default
def DateRealToDB(date):
    date = date.split('-')
    return datetime.date(int(date[0]), int(date[1]), int(date[2]))

def DateTimeRealToDB(value):
    value = value.split(' ')
    date = value[0].split('-')
    time = value[1].split(':')
    second = time[2].split('.')
    return datetime.datetime(int(date[0]), int(date[1]), int(date[2]),int(time[0]),int(time[1]),int(second[0]),int(second[1]))

optionCate = {}
def ListOptionCate(id=0, split=None, level=None, first=None):
    global optionCate
    if first:
        optionCate = {}
    if split:
        split += "=="
    arrCate = VCate.gql("WHERE parent_id=" + str(id))
    if arrCate:
        for cate in arrCate:
            id = int(cate.key().id())
            if split: 
                optionCate[len(optionCate)] = {'value':id, 'key':split + cate.title}
            else:
                optionCate[len(optionCate)] = {'value':id, 'key':cate.title}
            if level is None:
                ListOptionCate(id, split)
    return optionCate    

def Permission(get=None):
    user = users.GetCurrentUser()
    if user is None:
        return None
    member = None
    members = VMember.gql("WHERE user= :1 and status = 1 ", user)
    member = members.get()
    if member:
        if get is None:
            return user
        else:
            return  member
    else:
        member = CreateMember(None)
        if member is None:
            return http.HttpResponseRedirect('/user/vmember/add')
        return member

def CountMember(name):
    members = VMember.gql("WHERE name=:1",name)
    return members.count()

def CheckNickName(name):
    if len(name) > 3 and len(name) < 33 :
        if re.match("^[a-zA-Z0-9\\.\\-\\_]+$", name) != None:
            return True
    return False

def CreateMember(name):
    user = users.GetCurrentUser()
    if name is None:
        name  = user.nickname()
    name = name.replace(' ','')    
    name = name.lower()
    check = CheckNickName(name)
    
    if check is False :
        return None
    else:
        count = CountMember(name)
        if count == 0 :
            member = VMember()
            member.name = name    
            member.put()
            return member
        else:
            return None
def isAdmin():
    user = users.GetCurrentUser()
    if users.IsCurrentUserAdmin():
        return 1
    else:
        return None
